# -*- coding: utf-8 -*-
#-----------------------------------------------------------
#
# Saga Tools
# Copyright (C) 2011  Gianluca Massei
# EMAIL: g_massa (at) libero.it
# WEB  : http://www.geonomica.org
#
# Integrate Saga tools into qgis
#
#-----------------------------------------------------------
#
# licensed under the terms of GNU GPL 2
#
#---------------------------------------------------------------------

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import resources_rc
import os, sys
import saga_api,  fnmatch

import saga_parser

# Set up current path, so that we know where to look for mudules
#currentPath = os.path.dirname( __file__ )


modulepath='/usr/local/lib/saga/'

class SagaToolsPlugin:
  def __init__( self,iface ):
    self.iface = iface
    try:
      self.QgisVersion = unicode( QGis.QGIS_VERSION_INT )
    except:
      self.QgisVersion = unicode( QGis.qgisVersion )[ 0 ]


  def initGui( self ):
    if int( self.QgisVersion ) < 1:
      QMessageBox.warning( self.iface.getMainWindow(), "SagaTools",
      QCoreApplication.translate( "SagaTools", "Quantum GIS version detected: " ) +unicode( self.QgisVersion )+".xx\n"
      + QCoreApplication.translate( "SagaTools", "This version of Saga Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled." ) )
      return None
      
    libraries=[]
    librariesList = os.listdir(modulepath)
    mlb= saga_api.CSG_Module_Library()

    self.menu = QMenu()
    self.menu.setTitle( QCoreApplication.translate( "SagaTools", "&Saga GIS" ) )
    
    for fmlb in librariesList:
        if fnmatch.fnmatch(fmlb, '*.so'):
            self.library=self.menu.addMenu(fmlb.strip('.so'))
            mlb.Create(saga_api.CSG_String(modulepath+fmlb))
            for i in range(mlb.Get_Count()):
                m = mlb.Get_Module(i)
                self.module=QAction( QCoreApplication.translate("SagaTools", m.Get_Name()), self.iface.mainWindow() )
                menuItem_module = self.library.addAction(m.Get_Name())
                receiver = lambda fmlb=fmlb,  mname=m.Get_Name(): self.onModule(fmlb, mname)
                QObject.connect(menuItem_module, SIGNAL('triggered()'), receiver) 
                self.library.addAction(menuItem_module)
 
    menu_bar = self.iface.mainWindow().menuBar()
    actions = menu_bar.actions()
    lastAction = actions[ len( actions ) - 1 ]
    menu_bar.insertMenu( lastAction, self.menu )

  def onModule( self, fmlb, mname ):
    fmlb    = modulepath  + fmlb
    saga_parser.list_param_module(fmlb, mname)

  def unload( self):
    pass
